<?php
/**
 * 日志
 */

namespace Piz;

class Log
{
    /**
     * 实例
     * @var object
     */
    private static $instance;
    /**
     * 配置参数
     * @var array
     */
    private static $config = [];

    private static $logs = [];

    private function __construct()
    {
    }

    public static function get_instance()
    {
        if (is_null(self::$instance)) {
            self::$config = Config::get_instance()->get('app.log');
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * write 方法别名
     * @param       $type
     * @param array ...$logs
     */
    public function logs($type, ...$logs)
    {
        $this->write($type, ...$logs);
    }

    /**
     * 写入日志
     * @param       $type
     * @param array ...$msg
     */
    public function write($type, ...$logs)
    {
        $type = strtoupper($type);
        if (is_array($logs) || is_object($logs)) {
            $content = var_export($logs, true);
        }
        $content = date('Y-m-d H:i:s') . "--------" . $content . " \n ";
        @file_put_contents(LOG_PATH . 'swoole.log', $content, FILE_APPEND);
        $msg = "{$type} \t " . date("Y-m-d h:i:s") . " \t " . join(" \t ", $logs);
        if (!in_array($type, self::$config['level'])) return false;
        if (self::$config['echo']) {
            echo $msg, PHP_EOL;
        }
        $this->save([$type => [$msg]]);
        //self::$logs[$type][] = $msg;
    }

    /**
     * swoole异步写入日志信息
     * @param mixed $msg 调试信息
     * @param string $type 信息类型
     * @return bool
     */
    public function save($log)
    {
        if (empty($log)) return false;
        foreach ($log as $type => $logs) {
            $dir_path = LOG_PATH . date('Ymd') . DIRECTORY_SEPARATOR;
            !is_dir($dir_path) && mkdir($dir_path, 0777, TRUE);
            $type = 'COMM';
            $filename = date("D") . '.' . $type . '.log';

            $content = NULL;
            foreach ($logs as $log) {
                $content .= $log . PHP_EOL;
            }
            @file_put_contents($dir_path . $filename, $content, FILE_APPEND);
            //swoole_async_writefile($dir_path.$filename , $content, NULL, FILE_APPEND);
        }
        //self::$logs = [];
        return true;
    }
}